package com.ruoyi.huanjing.tool;

import com.ruoyi.huanjing.entity.Atmospheric;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalDouble;

public class ModisDataParser {
    private static final double NODATA_VALUE = -99.0;
    private static final int SKIP_LINES = 6;
    private static final int ROWS = 360;
    private static final int COLS = 720;

    private double[][] data;
    private Map<String, Object> result;

    public Map<String, Object> parseAndProcess(String filePath) throws IOException {
        data = parseModisData(filePath);
        long validTime = System.currentTimeMillis();
        return processModisData(data, validTime);
    }

    /**
     * 解析MODIS ASCII数据文件
     * @param filePath 文件路径
     * @return 二维数组表示的栅格数据
     * @throws IOException 文件读取异常
     */
    private double[][] parseModisData(String filePath) throws IOException {
        List<double[]> dataList = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            int lineCount = 0;

            // 跳过脚本部分
            while ((line = br.readLine()) != null && lineCount < SKIP_LINES) {
                lineCount++;
            }

            // 读取数据部分
            while ((line = br.readLine()) != null) {
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }

                // 分割每行数据并转换为double数组
                String[] values = line.trim().split("\\s+");
                double[] row = new double[values.length];

                for (int i = 0; i < values.length; i++) {
                    double value = Double.parseDouble(values[i]);
                    // 将无效值替换为NaN
                    row[i] = (value == NODATA_VALUE) ? Double.NaN : value;
                }

                dataList.add(row);
            }
        }

        // 转换为二维数组
        return dataList.toArray(new double[0][]);
    }

    /**
     * 处理MODIS数据并转换为地理坐标点列表
     * @param data MODIS数据二维数组
     * @param validTime 数据有效时间戳(毫秒)
     * @return 结构化数据结果
     */
    private Map<String, Object> processModisData(double[][] data, long validTime) {
        // 初始化结果列表
        List<Atmospheric> tempDataList = new ArrayList<>();

        // 初始化边界值
        OptionalDouble minLonResult = OptionalDouble.of(180.0);
        OptionalDouble maxLonResult = OptionalDouble.of(-180.0);
        OptionalDouble minLatResult = OptionalDouble.of(90.0);
        OptionalDouble maxLatResult = OptionalDouble.of(-90.0);

        // 初始化数值范围
        OptionalDouble minVal = OptionalDouble.empty();
        OptionalDouble maxVal = OptionalDouble.empty();

        // 遍历数据生成Atmospheric对象
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data[row].length; col++) {
                double value = data[row][col];

                // 跳过无效值
                if (Double.isNaN(value) || value == NODATA_VALUE) {
                    continue;
                }

                // 计算经纬度 (基于360x720网格)
                double currentLat = 90.0 - row * 0.5;  // 纬度从90°N到90°S
                double currentLon = col * 0.5 - 180.0; // 经度从180°W到180°E

                // 更新边界
                minLonResult = OptionalDouble.of(Math.min(minLonResult.getAsDouble(), currentLon));
                maxLonResult = OptionalDouble.of(Math.max(maxLonResult.getAsDouble(), currentLon));
                minLatResult = OptionalDouble.of(Math.min(minLatResult.getAsDouble(), currentLat));
                maxLatResult = OptionalDouble.of(Math.max(maxLatResult.getAsDouble(), currentLat));

                // 更新数值范围
                if (!minVal.isPresent() || value < minVal.getAsDouble()) {
                    minVal = OptionalDouble.of(value);
                }
                if (!maxVal.isPresent() || value > maxVal.getAsDouble()) {
                    maxVal = OptionalDouble.of(value);
                }

                // 创建并添加数据点
                Atmospheric atmospheric = new Atmospheric();
                atmospheric.setLon(BigDecimal.valueOf(currentLon));
                atmospheric.setLat(BigDecimal.valueOf(currentLat));
                atmospheric.setValue(BigDecimal.valueOf(value));
                atmospheric.setTime(BigDecimal.valueOf(validTime));
                tempDataList.add(atmospheric);
            }
        }

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("dataList", tempDataList);

        Map<String, Double> bounds = new HashMap<>();
        bounds.put("minLon", minLonResult.getAsDouble());
        bounds.put("maxLon", maxLonResult.getAsDouble());
        bounds.put("minLat", minLatResult.getAsDouble());
        bounds.put("maxLat", maxLatResult.getAsDouble());
        result.put("bounds", bounds);

        // 添加数据值的最大值和最小值
        Map<String, Double> valueRange = new HashMap<>();
        valueRange.put("minValue", minVal.getAsDouble());
        valueRange.put("maxValue", maxVal.getAsDouble());
        result.put("valueRange", valueRange);

        return result;
    }
}